import { Injectable, NestMiddleware } from '@nestjs/common';
import { AuthService } from 'src/Auth/auth.service';
import { AuthorizationException } from 'src/exception/AuthorizationException';

@Injectable()
export class AuthMiddleware implements NestMiddleware {
  constructor(private readonly auth: AuthService) {}
  async use(req: Request, res: Response, next: () => void) {
    if (req.method === 'GET') return next();
    const token: string = req.headers['authorization'];
    if (!token) throw new AuthorizationException('无效的token！');
    if (!token.includes('Bearer'))
      throw new AuthorizationException('无效的token！');
    if (await this.auth.verify(token)) next();
    else throw new AuthorizationException('无效的token！');
  }
}
